package com.shenmazong.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shenmazong.dto.TbJob;
import org.redisson.Redisson;
import org.redisson.api.LocalCachedMapOptions;
import org.redisson.api.RLocalCachedMap;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @author 阿瑞
 * @version 1.0
 * @description TODO
 * @class JobReceive ???
 * @date 2021/9/25 20:06
 */
@Component
public class JobReceive {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private Redisson redisson;
    @RabbitListener(queues = MqConfig.JOB_QUEUE)
    public void  receiveJob(String msg){
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap<String,String> map=null;
        try {
            map = objectMapper.readValue(msg, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        RLocalCachedMap<String, String> botian = redisson.getLocalCachedMap("job", LocalCachedMapOptions.defaults());
        List list = null;
        try {
            list = objectMapper.readValue(botian.get("job"), List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (map.get("saveJob")!=null){
            String saveJob = map.get("saveJob");
            try {
                TbJob job = objectMapper.readValue(saveJob, TbJob.class);
                job.setJobAudit((byte) 1);
                elasticsearchRestTemplate.save(job);
                list.add(job);
                String s = objectMapper.writeValueAsString(list);
                botian.put("job",s);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else{
            String s = map.get("delJob");
            for (Object o : list) {
                try {
                    String s1 = objectMapper.writeValueAsString(o);
                    TbJob job = objectMapper.readValue(s1, TbJob.class);
                    if (job.getJobId()==Long.parseLong(s)){
                        job.setDeleteFlag((byte) 1);
                        elasticsearchRestTemplate.save(job);
                        list.remove(o);
                    }
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
            try {
                botian.put("job",objectMapper.writeValueAsString(list));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }
}
